package com.mygame.xinyue;

import com.mygame.common.component.BaseRoute;
import com.mygame.common.component.RouteComponent;
import com.mygame.common.utils.PathUtil;
import com.mygame.common.utils.PropertyReader;
import com.mygame.message.nats.NatsGatewayMessageConsumerService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mygame.dao.AsyncPlayerDao;
import com.mygame.message.dispatcher.DispatchGameMessageService;
import com.mygame.message.context.ServerConfig;
import com.mygame.message.handler.GameChannelIdleStateHandler;
import com.mygame.xinyue.common.GameMessageDispatchHandler;

import java.util.Collection;

@SpringBootApplication(scanBasePackages = {"com.mygame"})
@EnableMongoRepositories(basePackages = {"com.mygame"}) // 负责连接数据库
public class XinyueGameServerMain {

    public static void main(String[] args) throws Exception{
        String configPath = PathUtil.getConfigBasePath("game_logic");
        PropertyReader.addFolder(configPath);
        PropertyReader.init();

//        String property = System.getProperty("user.dir");
//        JSONObject config = JsonUtils.read("D:\\work\\my\\java\\book-code-master\\my-game-server\\my-game-xinyue\\src\\main\\resources\\config\\env\\dev",
//                "nodes.json");

        ApplicationContext context = SpringApplication.run(XinyueGameServerMain.class, args);//初始化spring boot环境
        ServerConfig serverConfig = context.getBean(ServerConfig.class);//获取配置的实例
        DispatchGameMessageService.scanGameMessages(context, serverConfig.getServiceId(), "com.mygame");// 扫描此服务可以处理的消息
        NatsGatewayMessageConsumerService gatewayMessageConsumerService = context.getBean(NatsGatewayMessageConsumerService.class);//获取网关消息监听实例
        //PlayerDao playerDao = context.getBean(PlayerDao.class);//获取Player数据操作类实例
        AsyncPlayerDao playerDao = context.getBean(AsyncPlayerDao.class);
        DispatchGameMessageService dispatchGameMessageService = context.getBean(DispatchGameMessageService.class);

        gatewayMessageConsumerService.start((gameChannel) -> {//启动网关消息监听，并初始化GameChannelHandler
            // 初始化channel
            gameChannel.getChannelPiple().addLast(new GameChannelIdleStateHandler(300, 300, 300));
            gameChannel.getChannelPiple().addLast(new GameMessageDispatchHandler(context, serverConfig, dispatchGameMessageService, playerDao));
        }, serverConfig.getServerId());

        GameEngine.createApp("","","");
        GameEngine.me().addComponent(new RouteComponent());
        Collection<BaseRoute> baseRoutes = SpringContext.getBeanListOfType(BaseRoute.class);
        GameEngine.me().route().putAll(baseRoutes);
    }

}
